package com.itaq.cheetah.serviceA.utils;

import com.itaq.cheetah.serviceA.config.io.FastStringWriter;

import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;

/**
 * 异常处理工具类
 *
 * @author L.cm
 */
public class ExceptionUtil extends cn.hutool.core.exceptions.ExceptionUtil {

	/**
	 * 将CheckedException转换为UncheckedException.
	 *
	 * @param e Throwable
	 * @return {RuntimeException}
	 */
	public static RuntimeException unchecked(Throwable e) {
		if (e instanceof Error) {
			throw (Error) e;
		} else if (e instanceof IllegalAccessException ||
			e instanceof IllegalArgumentException ||
			e instanceof NoSuchMethodException) {
			return new IllegalArgumentException(e);
		} else if (e instanceof InvocationTargetException) {
			return new RuntimeException(((InvocationTargetException) e).getTargetException());
		} else if (e instanceof RuntimeException) {
			return (RuntimeException) e;
		} else if (e instanceof InterruptedException) {
			Thread.currentThread().interrupt();
		}
		return new RuntimeException(e);
	}

	/**
	 * 将ErrorStack转化为String.
	 *
	 * @param ex Throwable
	 * @return {String}
	 */
	public static String getStackTraceAsString(Throwable ex) {
		FastStringWriter stringWriter = new FastStringWriter(200);
		ex.printStackTrace(new PrintWriter(stringWriter));
		return stringWriter.toString();
	}
}
